package com.lemon.smartsafety.ui.activity.fire.item.safemanage;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.Field;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.RefreshViewEntity;
import com.lemon.smartsafety.entity.common.EvidenceActionSheetType;
import com.lemon.smartsafety.entity.common.UploadFileItem;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.event.safe_manager.SafeItemRefreshEvent;
import com.lemon.smartsafety.entity.main.OptionItemVo;
import com.lemon.smartsafety.http.HttpBack;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.result.BaseMode;
import com.lemon.smartsafety.result.fire.SafeManageDetails;
import com.lemon.smartsafety.result.fire.SuperviseCompanyResult;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectBaseActivity;
import com.lemon.smartsafety.ui.activity.fire.FirefightingUtil;
import com.lemon.smartsafety.ui.adapter.common.SelectEvidenceAdapter;
import com.lemon.smartsafety.ui.adapter.safe.safe_manager.CheckResultAdapter;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.ToastUtils;
import com.lemon.smartsafety.utils.common.DateUtils;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class FireSafeManageAddActivity extends PhotoSelectBaseActivity {


    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @Bind(R.id.txt_title)
    TextView txtTitle;
    @Bind(R.id.lineAll)
    LinearLayout lineAll;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.metResultSelect)
    MaterialEditText metResultSelect;
    @Bind(R.id.rowResultSelect)
    TableRow rowResultSelect;
    @Bind(R.id.metCheckRemark)
    MaterialEditText metCheckRemark;
    @Bind(R.id.tl_basic_info)
    TableLayout tlBasicInfo;
    @Bind(R.id.mSelectRecycleView)
    RecyclerView mSelectRecycleView;
    @Bind(R.id.btn_submit)
    Button btnSubmit;
    @Bind(R.id.tr_button)
    TableRow trButton;
    @Bind(R.id.mainContainer)
    LinearLayout mainContainer;
    @Bind(R.id.metRemarkHint)
    MaterialEditText metRemarkHint;
    @Bind(R.id.metPeriod)
    MaterialEditText metPeriod;
    private SafeManageDetails safeManageDetails;
    private SuperviseCompanyResult.ResultEntity resultEntity;

    private OptionItemVo mSelectResult = null;

    private List<OptionItemVo> resultList = new ArrayList<>();

    private boolean isEdit = false;


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            resultEntity = (SuperviseCompanyResult.ResultEntity) getIntent().getSerializableExtra(BundleKey.FIRE_COMPANY_BASE_INFO);
            safeManageDetails = (SafeManageDetails) getIntent().getSerializableExtra(BundleKey.FIRE_COMPANY_SAFE_BASE_INFO);
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_fire_safe_manage_add;
    }

    @Override
    protected void initViews() {
        super.initViews();

        FirefightingUtil.fireInspectAdd(FireSafeManageAddActivity.this);
        setMaxSize(3);
        initEditView();

    }


    @Override
    protected void initTitle() {
        this.setBarTitle(R.string.safe_manager_prop);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
     /*   super.onCreateOptionsMenu(menu);
        boolean menuResult = super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_history, menu);
        return menuResult;
*/
        getMenuInflater().inflate(R.menu.menu_fire_close, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_fire_close) {
            //关闭检查
            FirefightingUtil.fireColose(FireSafeManageAddActivity.this);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(FireSafeManageAddActivity.class);
    }


    @Override
    protected void initListener() {
        super.initListener();
    }


    /**
     * 表单验证
     *
     * @return
     */
    private boolean validateForm() {
        /**
         * 检查部位
         */
        if (mSelectResult == null) {
            metResultSelect.setError(getString(R.string.safe_manager_pick_result));
            mHUDUtil.showErrorTip(getString(R.string.safe_manager_pick_result));
            return false;
        }

        return true;
    }

    @OnClick(R.id.btn_submit)
    protected void btnSubmitAction() {
        if (!validateForm()) {
            return;
        }
        getConfirmDialog(getString(R.string.is_submit), new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    doPostAction();
                }
            }
        }).show();

    }

    private void doPostAction() {
        final LemonRequestParams params = new LemonRequestParams("company_safe_manage_record", "record_id", "");

        params.put("handler", "com.lemon.fire_control.CompanySafeManageRecordAction");
        params.put("op", "new_company_safe_manage_record");


        params.put("_txtIdValues", "");
        params.put("record_id", "");

        params.put("user_id", mSharedPreferencesHelper.getUserId());
        //params.put("txtCheckPart", txtCheckPart, Field.TYPE_STRING);
        params.put("company_code", StringUtils.nullValue(resultEntity.getCompanyCode()));
        params.put("txtItemId", safeManageDetails.getItem_id(), Field.TYPE_INT);
        params.put("txtCheckTime", DateUtils.getCurrentYMDHMSDate(), Field.TYPE_DATE);
        params.put("txtCheckUser", mSharedPreferencesHelper.getUserName(), Field.TYPE_STRING);
        params.put("txtRemark", metCheckRemark.getText().toString().trim(), Field.TYPE_STRING);
        String result = String.format("%s,%s", StringUtils.nullValue(mSelectResult.getVoId()), StringUtils.nullValue(mSelectResult
                .getTitle()));
        params.put("txtCheckResult", result, Field.TYPE_STRING);
        params.put("_txtDataSourceProvider", "com.lemon.fire_control.SafeConnProvider");
        params.put("_no_html", "1");

        getUploadItems(new SelectEvidenceAdapter.CropCallBack<List<UploadFileItem>>() {
            @Override
            public void onStart() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mHUDUtil.showHUD();
                    }
                });
            }

            @Override
            public void onFinish(List<UploadFileItem> data) {
                if (data != null && data.size() != 0) {
                    for (int i = 0; i < data.size(); i++) {
                        if (i == 0) {
                            params.put("picture1", data.get(i).getBase64());
                        } else if (i == 1) {
                            params.put("picture2", data.get(i).getBase64());
                        } else if (i == 2) {
                            params.put("picture3", data.get(i).getBase64());
                        }
                    }
                }
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        initCompanySave(params);
                    }
                });
            }
        });
    }


    /**
     * 保存
     */
    public void initCompanySave(LemonRequestParams params) {


        mHUDUtil.show();
        HttpOkBase.httpBasePost(params, HttpPath.getmBase(HttpPath.ActionServlet), "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {

                mHUDUtil.hidden();
                try {
                    if (httpClient) {
                        BaseMode baseMode = JsonUtils.fromJson(result, BaseMode.class);
                        if (!CommonUtil.objIsEmpty(baseMode)) {
                            if (HttpBack.httpBackError(baseMode)) {
                                ToastUtils.toastMsg(baseMode.getMsg());

                                AppService.getBus().post(new RefreshViewEntity(FireSafeManageAddActivity.class.getName()));
                                FirefightingUtil.fireColose(FireSafeManageAddActivity.this);
                            } else {
                                mHUDUtil.showErrorTip(baseMode.getMsg());
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }


    /**
     * 处理所有的网络请求返回
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(final HttpCallbackEvent event) {
        if (EventTag.TAG_SAFE_MANAGER_SAVE_ACTION == event.getTag()) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.show();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            SafeItemRefreshEvent refreshEvent = new SafeItemRefreshEvent();
                            refreshEvent.setTag(SafeItemRefreshEvent.class.getName());
                            AppService.getBus().post(refreshEvent);
                            AppManager.getAppManager().finishActivity(FireSafeManageAddActivity.this);
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHUDUtil.hidden();
    }

    private void initEditView() {
        if (null == safeManageDetails) return;
        if (null == resultEntity) return;

        txtTitle.setText(resultEntity.getCompanyName());

        tvTitle.setText(StringUtils.nullValue(safeManageDetails.getItem_name(), ""));

        if (!CommonUtil.strIsEmpty(safeManageDetails.getRemark())) {
            metRemarkHint.setText(safeManageDetails.getRemark());
        }

        if (!CommonUtil.strIsEmpty(safeManageDetails.getCheck_freq() + safeManageDetails.getCheck_freq_unit_name())) {
            metPeriod.setText(safeManageDetails.getCheck_freq() + safeManageDetails.getCheck_freq_unit_name());
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.metResultSelect, R.id.rowResultSelect})
    public void onClick(View view) {
        showDialog(getResultList(safeManageDetails.getItem_options()));
    }

    private List<OptionItemVo> getResultList(String result) {
        resultList = new ArrayList<>();
        if (StringUtils.nullValue(result).length() != 0) {
            String[] arrs = result.split(",");
            if (arrs != null && arrs.length != 0) {
                for (int i = 0; i < arrs.length; i = i + 2) {
                    OptionItemVo vo = new OptionItemVo();
                    vo.setTitle(arrs[i + 1]);
                    vo.setVoId(arrs[i]);
                    resultList.add(vo);
                }
            }
        }
        return resultList;
    }


    private void showDialog(List<OptionItemVo> items) {
        new MaterialDialog.Builder(this).title(R.string.safe_manager_pick_result)
                .adapter(new CheckResultAdapter(items), new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                        mSelectResult = resultList.get(which);
                        metResultSelect.setText(mSelectResult.getTitle());
                        dialog.dismiss();
                    }
                })
                .show();
    }


    @Override
    public void evidencePlusEventHandler(String tag) {
        if (mPhotoList.size() >= 4 && mHUDUtil != null) {

            mHUDUtil.showErrorTip("最多只能选择3张图片信息");
            return;
        }
        if (this.getClass().getName().equals(tag)) {
            showActionSheet(EvidenceActionSheetType.CAMERA_ALBUM_MULTI);
        }
    }

}
